﻿var Controller = { 
//properties    
    QueryString             : { },
    watchtimer              : null,
    watcharray              : [],  
    IncludedFields          : 0,
    SidebarState            : 1, 
    SidebarUserDisplayState : 0, 
    EventOptionPanelState   : 10, 
    SelectedCategory        : -1,
    SelectedReport          : -1,
    SelectedCalendar        : -1,
    SelectedProperty        : -1,
    SelectedRoom            : -1,
    SelectedUser            : -1,
    LastRequestURL          : null,
    LastListURL             : null,
    DefaultFields           : 2767,
    SortField               : null,
    MailTo                  : null,
	pagesize				: 25,
    ConflictDates           : [],
    EventOptionPanels       : ['options','properties','categories','calendars','attachments','comments'],
    staron                  : "http://www.google.com/reader/ui/876134049-star_active.png",
    staroff                 : "http://www.google.com/reader/ui/945822248-star_inactive.png",
    
    
    
    dowatch : function ()
    {   
        var now = null;  
        for (var x in this.watcharray)
        { 
            now = this.watcharray[x].object[ this.watcharray[x].property ];  
            if (now != this.watcharray[x].value)
            { 
                this.watcharray[x].callback (now, this.watcharray[x].property); 
            }
            this.watcharray[x].value = now;
        }
    },
    
    watch : function (object, property, callback)
    {
        var data = { object : object, property : property, callback : callback };
        data['value'] = object[property];
        this.watcharray.push (data);
    },  
    
    parseUrl : function (url)
    {
        var value, data = url.split ('#');
        this.QueryString = { };
        if (data[1])
        {
            value = data[1].split ('/');
            for (var x=0;x<value.length;x+=2)
            {
                this.QueryString[value[x]] = value[x+1];
            }
        }
        return this.QueryString;
    } ,

    createQueryString : function  (namevalue)
    { 
        var tmp={ },output=[];
        for (var x in Controller.QueryString) tmp[x] = Controller.QueryString[x];
        for (var x in namevalue) tmp[x] = namevalue[x];
        for (var x in tmp) output.push (x + '/' + tmp[x].replace (/\s+/g, '+'));
        return output.join ('/');
    } ,
    
    setvalue : function (name, value)
	{
		this[name]=value;
		Controller.Reload();
	},
    
    
// methods    
    Clear    : function () { window.isbusy=false; if (window.disabler) window.disabler.invoke (window.isbusy); },
	
    has      : function (x) { return Controller.IncludedFields & EventObject.params.pos (x); },
    
    findpanel  : function (x) { for (var i in Controller.EventOptionPanels) if (Controller.EventOptionPanels[i]==x) return i; },
    
    getmode  : function (x) { return Controller.EventOptionPanelState & Math.pow (2, Controller.findpanel(x)); },
    
    setmode  : function (x) 
    { 
        var i=Math.pow (2, Controller.findpanel(x));
        Controller.EventOptionPanelState = bite (Controller.EventOptionPanelState, i); 
        setCookie('panels', Controller.EventOptionPanelState); 
        Controller.Reload('dcevent');
    },
    
    Reload   : function () 
    { 
        var dc, args=Controller.Reload.arguments,id=[];
        for (var x=0;x<args.length;x++)
        {
            dc=getElement (args[x]);
            if (dc) id.push (dc.scrollTop);
        } 
        Controller.mvcevents[window.mvcevent].invoke(); 
        for (var x=0;x<id.length;x++)
        {
            dc=getElement (args[x]);
            if (dc) dc.scrollTop = id[x];
        } 
    },  

    start : function  ()
    { 
	    this.watchtimer = window.setInterval ('Controller.dowatch()', 250);
    } 
 }  

var ReadyState = {     
    SENDING     : 1,  
    LOADING     : 2, 
    PROCESSING  : 3, 
    DONE        : 4
}  
 
window.processmessage       = 'Processing response...';  
window.eventlistxml         = null;  
window.currentevent         = null;  
window.invoice              = null;  
window.dom                  = XmlDocument.create();  
window.http                 = XmlHttp.create();  
window.request              = CustomAJAXConnector.create();
window.rooms                = [];  
window.folders              = [];  
window.reports              = [];  
window.properties           = [];  
window.calendars            = [];  
window.loggedinuser         = [];  
window.eventlog             = [];  
window.users                = []; 
window.property_types       = [];  
window.gridview             = dgrid.LIST;  
window.searchmode           = 0; 
var APPLICATION_NAME        = 'EventBuilder Personal Editionv6.1';   
var LOCATION_PATH_NAME      = location.pathname.split ('/');       
LOCATION_PATH_NAME.pop();
LOCATION_PATH_NAME			= LOCATION_PATH_NAME.join ('/');
var DATA_URL                = LOCATION_PATH_NAME + '/database/';  
var PAGE_SIZE               = 5;  
var TOTALBYTES              = 0;   
var ParseIdFromQuery        = parse4ID;
var SCHEME = {
	body : {
		backcolor : 'FFFFFF',
		bandcolor : 'D2E6D2',
		forecolor : '000000',
		linkcolor : '003366'
	},
	panel : {
		main : {
			backcolor : 'D2E6D2',
			bandcolor : 'D2E6D2',
			forecolor : '000000',
			linkcolor : '003366'
		},
		side : {
			backcolor : 'D0D0EE',
			bandcolor : 'BCBCDD',
			forecolor : '000000',
			linkcolor : '003366'
		}
	}
}
 
// -----------------------------------------------------------------------'
// LoginRequest
// -----------------------------------------------------------------------'
// LOGIN method loads when Sign In button is clicked and  
// calls the LOGIN action on the server to look up the  
// current user by userid and password  
// --------------------------------------------------------'  
// LoginRequest.Load() 
function login (user, pass, keepuser, keeppass)  
{    
    var Connector = { 
                'params' : { 'action' : 'login', 'uid' : user, 'pass' : pass, 'ku' : keepuser, 'kp' : keeppass },
                'target' : window.loggedinuser,
                'message' : 'processing login...',
                'serializer' : function (target, data) { window.loggedinuser = new MVCUser(data); },
                'aftersend' : ValidateLogin,
                'beforesend' : BeforeLogin,
                'onreceive' : function () {  var lo=getElement ('loginstatus'); if (lo) lo.innerHTML = "Waiting for response..."; } 
              };
    window.request.create (Connector);    
}  
// -----------------------------------------------------------------------'

function BeginPageLoading ()
{ 
    var Connectors=[];
    Connectors.push (LoadGlobalRoomsList (null, true)); 
    Connectors.push (LoadGlobalCategoryList (null, true)); 
    Connectors.push (LoadGlobalUserList (null, true));
    Connectors.push (LoadGlobalPropertyList (null, true));
    Connectors.push (LoadGlobalCalendarList (null, true));
    Connectors.push (LoadGlobalPropertyTypeList (true));
    Connectors.push (LoadGlobalConfigList (null, true));  
    Connectors.push (LoadGlobalReportList (null, true));  
    
    Controller.watch (location, 'href', handleQueryString); 
    Controller.start();
    window.isbusy = true;
    window.disabler.invoke (window.isbusy);
    window.connector.oncomplete = function () { Controller.Clear(); if (!handleQueryString (location.href, null, true)) LoadNext5Events(); }
    window.connector.send (Connectors);
} 



function handleQueryString (url, id, onloaded)
{  
    Controller.parseUrl (url); 
    var command = onloaded ? GetFunctionFromURL (url) : GetFunctionFromClick (url);
    if (command)
    {
        command (); 
        return true;
    }
    return false;
} 




function GetFunctionFromURL (url)
{  
    Controller.parseUrl (url); 
    var command;
    if (command = GetDatasourceFunctionFromURL ())
    {
        return command;
    }
    return false;
} 

 

function GetFunctionFromClick (url)
{  
    Controller.parseUrl (url); 
    var command, event, lense, setting; 
    if (lense = GetViewFunctionFromURL ())
    {
        lense ();
    } 
    
    if (setting = GetSettingFunctionFromURL ())
    {
        setting ();
    } 
     
    
    if (event = Controller.QueryString['key'])
    {// when loading from Click, assume datasources are loaded   
     // and load OnClick object event handlers first
        return function () { EventDataGridEdit (null, event)  ; }  
    } 
     
    if (command = GetDatasourceFunctionFromURL ())
    {
        return command;
    }
    
    
    return false;
}  



function GetDatasourceFunctionFromURL ()
{  
    var action  = Controller.QueryString['report'];
    var id      = Controller.QueryString['id'];
    var view    = Controller.QueryString['view']; 
    
    if (action)
    {
        switch(action)
        {
            case 'next5':
                return LoadNext5Events;
                break;
            case 'feature':
                return LoadFeaturedEvents; 
                break;
            case 'my':
                return function () { SearchEventsByUser(window.loggedinuser.id); }
                break;
            case 'byuser':
                return function () { SearchEventsByUser(id); } 
                break;
            case 'search':
                return function () { SearchEventsEx (); }
                break;
        }
    }
    else if (id)
    {
        switch(view)
        {
            case 'roomlist':
                return function () { Controller.SelectedRoom = id; RoomListEvent.invoke();  };
                break; 
            case 'userlist':
                return function () { Controller.SelectedUser = id; UserListEvent.invoke();  };
                break; 
//            case 'settingspage':
//                confirm(RenderSettingsPage.Setting)
//                switch(RenderSettingsPage.Setting)
//                {
//                    case RenderSettingsPage.CATEGORY:
//                        return function () { Controller.SelectedCategory = id; Controller.Reload (); };
//                        break;
//                }
//                break; 
        }
    } 
    return false;
}  

function GetViewFunctionFromURL ()
{  
    var view = Controller.QueryString['view'];
    if (view)
    { 
        return function () { Controller.mvcevents[view].invoke(); } 
    } 
    return false;
} 

function GetSettingFunctionFromURL ()
{  
    var setting = Controller.QueryString['setting'];
    if (setting)
    { 
        return function () { RenderSettingsPage.Setting = setting; SettingsPageEvent.invoke(); } 
    } 
    return false;
} 


function GetClickFunctionFromURL ()
{  
    var action  = Controller.QueryString['report'];
    var id      = Controller.QueryString['id'];
} 

// -----------------------------------------------------------------------'
// PasswordResponse
// -----------------------------------------------------------------------'
// PasswordResponse.Load() 
function remind (e)  
{     
    var Connector = { 
                'params' : { 'action' : 'remind', 'e' : e }, 
                'aftersend' : function () { toggle("passInfo"); } 
              }; 
    window.request.create (Connector);
}    
// -----------------------------------------------------------------------'


// -----------------------------------------------------------------------'
// GlobalPropertyTypeList
// -----------------------------------------------------------------------'
// GlobalPropertyTypeList.Load()  
function LoadGlobalPropertyTypeList (batch)
{
    var Connector = { 
                'params' : { 'action' : 'dump', 'op' : 'xms', 'id' : 'ebp_event_property_types' },
                'target' : window.property_types,
                'aftersend' : LoadNext5Events,
                'message' : 'loading property type list...',
                'rowname' : 'r',
                'columnname' : 'n'
              };
    if (batch) return Connector;
    else window.request.create (Connector); 
}   
// -----------------------------------------------------------------------'


// -----------------------------------------------------------------------'
// GlobalPropertyList
// -----------------------------------------------------------------------'
// GlobalPropertyList.Load() 
function LoadGlobalPropertyList (callback, batch)  
{    
	window.properties = [];
    var Connector = { 
                'params' : { 'action' : 'property' },
                'target' : window.properties,
                'serializer' : CustomPropertyElement.targetmask,
                'aftersend' : callback || LoadGlobalCalendarList,
                'message' : 'loading property list...',
                'rowname' : 'r',
                'columnname' : 'n'
              };
    if (batch) return Connector;
    else window.request.create (Connector);  
}    
// -----------------------------------------------------------------------'


// -----------------------------------------------------------------------'
// GlobalUserList 
// -----------------------------------------------------------------------'  

// GlobalUserList.Load() 
function LoadGlobalUserList (callback, batch)  
{   
	window.users = [];
    var Connector = { 
                'params' : { 'action' : 'dump', 'op' : 'xms', 'id' : 'event_users' },
                'target' : window.users, 
                'aftersend' : callback || LoadGlobalPropertyList,
                'message' : 'loading user list...',
                'rowname' : 'r',
                'columnname' : 'n'
              };
    if (batch) return Connector;
    else window.request.create (Connector);  
}  

// GlobalUserList.ReLoad() 
function ReLoadGlobalUserList ()  
{   
    if (window.http.readyState==ReadyState.DONE)
    {
        Controller.Clear();     
        Controller.SelectedUser = ParseIdFromQuery (window.http.responseText); 
	    LoadGlobalUserList (function () { Controller.Reload(); })  
    }
    Controller.Reload();
} 
// -----------------------------------------------------------------------'


// -----------------------------------------------------------------------'
// GlobalRoomsList 
// -----------------------------------------------------------------------'
// GlobalRoomsList.Load() 
function LoadGlobalRoomsList (callback, batch)  
{    
	window.rooms = [];
    var Connector = { 
                'params' : { 'action' : 'dump', 'op' : 'xms', 'id' : 'rooms' },
                'target' : window.rooms, 
                'aftersend' : callback || LoadGlobalCategoryList,
                'message' : 'loading rooms list...',
                'rowname' : 'r',
                'columnname' : 'n'
              };
    if (batch) return Connector;
    else window.request.create (Connector); 
}   

// GlobalRoomsList.ReLoad() 
function ReLoadGlobalRoomsList ()  
{   
    if (window.http.readyState==ReadyState.DONE)
    {
        Controller.Clear();     
        Controller.SelectedRoom = ParseIdFromQuery (window.http.responseText);  
	    LoadGlobalRoomsList (function () { Controller.Reload(); });     
    }
    Controller.Reload();
}
// -----------------------------------------------------------------------'


// -----------------------------------------------------------------------'
// GlobalReportList 
// -----------------------------------------------------------------------'
// GlobalReportList.Load() 
function LoadGlobalReportList (callback, batch)  
{   
	window.reports = [];
    var Connector = { 
                'params' : { 'action' : 'dump', 'op' : 'xms', 'id' : 'customreports' },
                'target' : window.reports, 
                'aftersend' : callback || LoadGlobalUserList,
                'message' : 'loading report list...',
                'rowname' : 'r',
                'columnname' : 'n'
              };
    if (batch) return Connector;
    else window.request.create (Connector); 
}    

// GlobalReportList.ReLoad() 
function ReLoadGlobalReportList()  
{   
    if (window.http.readyState==ReadyState.DONE)   
    {  
        Controller.SelectedReport = 0;
        Controller.Clear();    
	    LoadGlobalReportList (function () { Controller.Reload(); });  
    }   
}   
// -----------------------------------------------------------------------'



// -----------------------------------------------------------------------'
// GlobalCategoryList 
// -----------------------------------------------------------------------'
// GlobalCategoryList.Load() 
function LoadGlobalCategoryList (callback, batch)  
{   
	window.folders = [];
    var Connector = { 
                'params' : { 'action' : 'dump', 'op' : 'xms', 'id' : 'eventfolders' },
                'target' : window.folders, 
                'aftersend' : callback || LoadGlobalReportList,
                'message' : 'loading category list...',
                'rowname' : 'r',
                'columnname' : 'n'
              };
    if (batch) return Connector;
    else window.request.create (Connector); 
}    

// GlobalCategoryList.ReLoad() 
function ReLoadGlobalCategoryList ()  
{   
    if (window.http.readyState==ReadyState.DONE)   
    {  
        Controller.SelectedCategory = 0;
        Controller.Clear();    
	    LoadGlobalCategoryList (function () { Controller.Reload(); });  
    }   
}   
// -----------------------------------------------------------------------'


// -----------------------------------------------------------------------'
// GlobalCalendarList 
// -----------------------------------------------------------------------'
// GlobalCalendarList.Load() 
function LoadGlobalCalendarList (callback, batch)  
{   
	window.calendars = [];
    var Connector = { 
                'params' : { 'action' : 'dump', 'op' : 'xms', 'id' : 'ebp_event_calendars' },
                'target' : window.calendars, 
                'aftersend' : callback || LoadGlobalConfigList,
                'message' : 'loading calendar list...',
                'rowname' : 'r',
                'columnname' : 'n'
              };
    if (batch) return Connector;
    else window.request.create (Connector); 
}   
// -----------------------------------------------------------------------'

// -----------------------------------------------------------------------'
// IssueLogList 
// -----------------------------------------------------------------------'
// IssueLogList.Load() 
function LoadIssueLogList ()  
{    
    window.rss = [];
    window.request.load (window.rss, function () { ErrorLogEvent.invoke() }, 'description'); 
    window.request.columnname = null;
    window.request.send ({ 'rss' : 'xml' }); 
}    
// -----------------------------------------------------------------------'
 

// -----------------------------------------------------------------------'
// GlobalConfigList 
// -----------------------------------------------------------------------'
// GlobalConfigList.Load() 
function LoadGlobalConfigList (callback, batch)  
{ 
    var response = function () { LoadGlobalPropertyTypeList (); };
    var Connector = { 
                'params' : { 'action' : 'get_config' },
                'target' : window.config,
                'aftersend' : callback || response,
                'message' : 'loading program options...',
                'serializer' : function (target, data) 
				{ 
				   window.config = data; 
				   if (data['defaultfields'])
				   {
					   Controller.IncludedFields = parseInt(data['defaultfields']); 
				   } 
				}
              };
    if (batch) return Connector;
    else window.request.create (Connector);
} 

function OnSaveConfig()
{  
    if (window.http.readyState==ReadyState.DONE)   
    {        
        Controller.Clear();
        LoadGlobalConfigList (function () {Controller.Reload(); });    
    }              
} 
// -----------------------------------------------------------------------'


// -----------------------------------------------------------------------'
// FeaturedValueRequest 
// -----------------------------------------------------------------------'
// FeaturedValueRequest.Load() 
function LoadFeaturedValueRequest (eventid, value)  
{    
    var Connector = { 
                'params' : { 'action' : 'feature', 'id' : eventid, 'value' : value }, 
                'message' : 'loading featured value update...',
                'aftersend' : function () { DebugEventDataGrid.afterinvoke () }
              };
    window.request.create (Connector); 
}  
// -----------------------------------------------------------------------'




// -----------------------------------------------------------------------'
// EventConflictDateRange 
// -----------------------------------------------------------------------'
// EventConflictDateRange.Load() 
function LoadEventConflictDateRange (id)  
{       
    var Connector = { 
                'params' : { 'action' : 'range', 'id' : id },
                'rowname' : 'record',
                'columnname' : 'name', 
                'message' : 'loading date conflict list...',
                'onreceive' : OnConflictDatesReceive
              };
    window.request.create (Connector);  
} 
 
// RemoveCustomDateLink.Load() 
function RemoveCustomDateLink (id, date)
{
    var Connector = { 
                'params' : { 'action' : 'delete_custom', 'eventfk' : id, 'date' : date } ,
                'aftersend' : ProcessRemoveCustomDateLink
              };
    window.request.create (Connector);  
} 
 
// RemoveCustomDateLink.Receive() 
function ProcessRemoveCustomDateLink ()
{
    if (window.http.readyState==ReadyState.DONE)   
    {   
        var id = ParseIdFromQuery (window.http.responseText);  
        Controller.Clear();    
	    LoadEventConflictDateRange (id) ;
    }  
    Controller.Reload();      
}

function ProcessResetEventConflictDate ()
{  
    if (window.http.readyState==ReadyState.DONE)   
    {    
        Controller.ConflictDates = [];
        Controller.Clear();    
        window.currentevent.verify();
    }  
}

function SwapEventCustomDate (date, old, id)
{ 
    var scrolltop = document.getElementById('deventdateremove').scrollTop;
	SwapEventConflictDate (date, old, id, function (data)
	{
		//confirm (data);
		LoadEventDetailDateRange (function ()
		{
			//confirm (scrolltop);
			document.getElementById('deventdateremove').scrollTop = scrolltop;
		});
	});
}

function SwapEventConflictDate (date, old, id, callback)
{
    var uk = dateSQL (date); 
	HideTimeSelector();
    var Connector = { 
                'params' : { 'action' : 'swap_event_date', 'id' : id, 'date' : uk, 'old' : old } ,
                'aftersend' : callback || ProcessRemoveCustomDateLink
              };
    window.request.create (Connector); 
}

function ResetEventConflictDate (date, id)
{
    var uk = dateSQL (date);  
	HideTimeSelector();
    var Connector = { 
                'params' : { 'action' : 'reset_event_date', 'id' : id, 'date' : uk } ,
                'aftersend' : ProcessResetEventConflictDate
              };
    window.request.create (Connector); 
}

function ResetEventConflictTime (id, value, marker)
{  
	HideTimeSelector();
    var Connector = { 
                'params' : { 'action' : 'reset_event_time', 'id' : id, 'value' : value, 'marker' : marker } ,
                'aftersend' : ProcessResetEventConflictDate
              };
    window.request.create (Connector); 
} 
 
// -----------------------------------------------------------------------'
// EventDetailDateRange 
// -----------------------------------------------------------------------'
// EventDetailDateRange.Load() 
function LoadEventDetailDateRange (callback, batch)  
{     
	window.currentevent.CustomDates = [];
    var Connector = { 
                'params' : { 'action' : 'range', 'id' : window.currentevent.ID },
                'target' : window.currentevent.CustomDates, 
                'aftersend' : callback || function () { LoadEventDetailRoomList(); },
                'serializer' : function (target, data) { target.push ( new CustomDate (data['FriendlyDate'], data['CustomDate']) ); },
                'message' : 'loading event date list...',
                'onreceive' : function () { /*confirm(window.http.responseText);*/ EventDetailEvent.invoke(); }
              };
    if (batch) return Connector;
    else window.request.create (Connector);   
} 

// EventDetailDateRange.Reload() 
function LoadDateScope (s1,s2,tp,ui)  
{   
	window.currentevent.CustomDates = [];
    var Connector = { 
                'params' : { 'action' : 'scope', 's1' : s1, 's2' : s2, 'tp' : tp, 'ui' : ui },
                'target' : window.currentevent.CustomDates, 
                'aftersend' : function () { window.currentevent.DateListVisible=true; DebugEventDetailForm.invoke(); },
                'serializer' : function (target, data) { target.push ( new CustomDate (data['FriendlyDate'], data['CustomDate']) ); },
                'message' : 'loading event date list...',
                'onreceive' : function () { EventDetailEvent.invoke(); }
              };
    window.request.create (Connector);  
}   
// -----------------------------------------------------------------------' 


// -----------------------------------------------------------------------'
// EventDetailCalendarList 
// -----------------------------------------------------------------------'
// EventDetailCalendarList.Load() 
function LoadEventDetailCalendarList (batch)  
{   
	window.currentevent.EventCalendars = [];
    var Connector = { 
                'params' : { 'action' : 'calendar', 'id' : window.currentevent.ID },
                'target' : window.currentevent.EventCalendars,  
                'serializer' : function (target, data) { target.push ( EventCalendarObject ( data ) ); },
                'message' : 'loading event calendar list...',
                'onreceive' : function () { EventDetailEvent.invoke(); }
              };
    if (batch) return Connector;
    else window.request.create (Connector);  
} 
// -----------------------------------------------------------------------'


// -----------------------------------------------------------------------'
// EventDetailRoomList 
// -----------------------------------------------------------------------'
// EventDetailRoomList.Load() 
function LoadEventDetailRoomList (callback, batch)  
{    
	window.currentevent.Rooms = [];
    var Connector = { 
                'params' : { 'action' : 'roomlist', 'id' : window.currentevent.ID },
                'target' : window.currentevent.Rooms, 
                'aftersend' : callback || LoadEventDetailCommentList,
                'serializer' : function (target, data) { target.push ( new RoomObject (GetRoomName(data['roomfk']), data['roomfk']) ); },
                'message' : 'loading event rooms list...',
                'onreceive' : function () { EventDetailEvent.invoke(); }
              };
    if (batch) return Connector;
    else window.request.create (Connector); 
} 

// EventDetailRoomList.Build() 
function ProcessEventDetailRoomListEx (callback) // 3rd  
{   
    alert ('legacy method ProcessEventDetailRoomListEx called!!');             
}  

// EventConflictRoomList.Load() 
function CLLoadEventConflictRoomList (id)  
{    
	LoadEventConflictRoomList (id, CLLaunchRoomListDialog);
}  

// EventConflictRoomList.Load() 
function LoadEventConflictRoomList (id, callback)  
{               
    var Connector = { 
                'params' : { 'action' : 'roomlist', 'id' : id } ,
                'message' : 'loading conflicting event rooms list...',
                'aftersend' : callback || LaunchRoomListDialog
              };
    window.request.create (Connector);  
}  

// EventChangeRoomList.Load() 
function UpdateEventRoomList (id,rooms)  
{               
    var Connector = { 
                'params' : { 'action' : 'roomchange', 'id' : id, 'rooms' : rooms } ,
                'aftersend' : ProcessResetEventConflictDate
              };
    window.request.create (Connector);   
} 
// -----------------------------------------------------------------------' 


// -----------------------------------------------------------------------'
// EventDetailCommentList 
// -----------------------------------------------------------------------'
// EventDetailCommentList.Load() 
function LoadEventDetailCommentList (callback, batch)  
{         
	window.currentevent.EventComments = [];
    var Connector = { 
                'params' : { 'action' : 'comments', 'id' : window.currentevent.ID },
                'target' : window.currentevent.EventComments, 
                'aftersend' : callback || LoadEventDetailAttachments,
                'serializer' : function (target, data) { target.push ( new EventComment (data) ); },
                'message' : 'loading event comment list...',
                'onreceive' : function () { EventDetailEvent.invoke(); }
              };
    if (batch) return Connector;
    else window.request.create (Connector); 
} 
// -----------------------------------------------------------------------'  



// -----------------------------------------------------------------------'
// EventDetaiAttachments
// -----------------------------------------------------------------------'
// EventDetaiAttachments.Load() 
function LoadEventDetailAttachments (callback, batch)  
{     
	window.currentevent.Attachments = [];
    var Connector = { 
                'params' : { 'action' : 'attach', 'id' : window.currentevent.ID },
                'target' : window.currentevent.Attachments, 
                'aftersend' : callback || LoadEventDetailCategoryList, 
                'message' : 'loading event attachment list...',
                'onreceive' : function () { EventDetailEvent.invoke(); }
              };
    if (batch) return Connector;
    else window.request.create (Connector);  
} 

// EventDetaiAttachments.Reload() 
function ReloadEventDetailAttachments ()  
{          
    LoadEventDetailAttachments (function () { Controller.Reload(); }); 
}  
// -----------------------------------------------------------------------'  


// -----------------------------------------------------------------------'
// EventDetailCategoryList 
// -----------------------------------------------------------------------'
// EventDetailCategoryList.Load() 
function LoadEventDetailCategoryList (callback, batch)  
{              
	window.currentevent.EventCategories = [];
    var Connector = { 
                'params' : { 'action' : 'category', 'id' : window.currentevent.ID },
                'target' : window.currentevent.EventCategories, 
                'aftersend' : callback || LoadEventDetailCalendarList, 
                'message' : 'loading event category list...',
                'serializer' : function (target, data) { target.push ( new EventCategory (data) ); },
                'onreceive' : function () { EventDetailEvent.invoke(); }
              };
    if (batch) return Connector;
    else window.request.create (Connector);   
}   

// EventDetailCategoryList.Build() 
function ProcessEventDetailCategoryListEx (callback) // 5th  
{   
    alert ('legacy method ProcessEventDetailCategoryListEx called!!');          
}  
// -----------------------------------------------------------------------' 


// -----------------------------------------------------------------------'
// EventLog 
// -----------------------------------------------------------------------'
// EventLog.Load() 
function OpenEventLog(id)  
{  
	window.eventlog = [];
    var Connector = { 
                'params' : { 'action' : 'log', 'id' : id },
                'target' : window.eventlog, 
                'message' : 'loading event log...',
                'aftersend' : function () { EventLogScreen.invoke (); } 
              };
    window.request.create (Connector);    
}  
// -----------------------------------------------------------------------'

 
function ReloadEventDetailAttachmentsEx ()  
{   
	if (window.http.readyState==ReadyState.DONE)
	{
		Controller.Clear();    
		ReloadEventDetailAttachments ();
	}
}


// Property.Create.Load() 
function CreateProperty (name)  
{  
    var cp = CustomPropertyElement.empty (name);
    cp.save ();
}   

// Room.Create.Load() 
function CreateRoom (name)  
{  
    var cp = RoomObject.empty (name, Controller.SelectedRoom > 0 ? Controller.SelectedRoom : 0);
    var Connector = {  
                'aftersend' : ReLoadGlobalRoomsList ,
                'message' : 'Receiving save response...',
                'method' : 'POST',
                'postdata' : RoomObject.Serialize (cp)
              }; 
    window.request.create (Connector);  
}  

// Category.Create.Load() 
function CreateCategory (name)  
{   
    var Connector = {  
                'aftersend' : ReLoadGlobalCategoryList ,
                'message' : 'Receiving create response...',
                'method' : 'POST',
                'postdata' : SerializeGeneric ('category', { 'title' : name, 'id' : 0, 'userfk' : window.loggedinuser.id } )
              }; 
    window.request.create (Connector);   
}  

// Report.Create.Load() 
function CreateReport (name)  
{   
    var Connector = {  
                'aftersend' : ReLoadGlobalReportList ,
                'message' : 'Receiving create response...',
                'method' : 'POST',
                'postdata' : SerializeGeneric ('report', { 'title' : name, 'id' : 0, 'templatebody' : '' } )
              }; 
    window.request.create (Connector);   
} 

// Category.Save.Load() 
function SaveReport (id, name, text)  
{   
    if (Controller.currentreportcontent)
	{
		var Connector = {  
					'aftersend' : ReLoadGlobalReportList ,
					'message' : 'Receiving save response...',
					'method' : 'POST',
					'postdata' : SerializeGeneric ('report', { 'title' : name, 'id' : id, 'templatebody' : Controller.currentreportcontent } )
				  }; 
		window.request.create (Connector);    
	} else confirm ('No currentreportcontent');
}   


// Category.Save.Load() 
function SaveCategory (id, name)  
{   
    var Connector = {  
                'aftersend' : ReLoadGlobalCategoryList ,
                'message' : 'Receiving save response...',
                'method' : 'POST',
                'postdata' : SerializeGeneric ('category', { 'title' : name, 'id' : id, 'userfk' : window.loggedinuser.id } )
              }; 
    window.request.create (Connector);    
}   

// Report.Delete.Load() 
function DeleteReport (id)  
{    
    var Connector = { 
                'params' : { 'action' : 'delete_report', 'id' : id }, 
                'aftersend' : ReLoadGlobalReportList,
                'message' : 'processing item delete...',
                'question' : 'delete this item' 
              };
    window.request.create (Connector); 
} 

// Property.Delete.Load() 
function DeleteProperty (id)  
{    
    var Connector = { 
                'params' : { 'action' : 'delete_property', 'id' : id }, 
                'aftersend' : CustomPropertyElement.OnSave,
                'message' : 'processing item delete...',
                'question' : 'delete this item' 
              };
    window.request.create (Connector); 
}

// Attachment.Delete.Load() 
function DeleteAttachment (id)  
{    
    var Connector = { 
                'params' : { 'action' : 'delete_attachment', 'id' : id }, 
                'aftersend' : ReloadEventDetailAttachmentsEx,
                'message' : 'processing item delete...',
                'question' : 'delete this item'
              };
    window.request.create (Connector);  
}

// Category.Delete.Load() 
function DeleteCategory (id)  
{    
    var Connector = { 
                'params' : { 'action' : 'delete_category', 'id' : id }, 
                'aftersend' : ReLoadGlobalCategoryList,
                'message' : 'processing item delete...',
                'question' : 'delete this item'
              };
    window.request.create (Connector);   
} 

// Room.Delete.Load() 
function DeleteRoom (id)  
{    
    var Connector = { 
                'params' : { 'action' : 'delete_room', 'id' : id }, 
                'aftersend' : ReLoadGlobalRoomsList,
                'message' : 'processing item delete...',
                'question' : 'delete this item'
              };
    window.request.create (Connector);   
} 

// User.Delete.Load() 
function DeleteUser (id)  
{    
    var Connector = { 
                'params' : { 'action' : 'delete_user', 'id' : id }, 
                'aftersend' : ReLoadGlobalUserList,
                'message' : 'processing item delete...',
                'question' : 'delete this item'
              };
    window.request.create (Connector);   
}

// Event.Delete.Load() 
function DeleteEvent (id)  
{    
    var Connector = { 
                'params' : { 'action' : 'delete_event', 'id' : id }, 
                'aftersend' : ReloadLastListRequest,
                'message' : 'processing item delete...',
                'question' : 'delete this item'
              };
    window.request.create (Connector);   
}

// Calendar.Delete.Load() 
function DeleteCalendar (id)  
{    
    var Connector = { 
                'params' : { 'action' : 'delete_calendar', 'id' : id }, 
                'aftersend' : EventCalendar.OnSave,
                'message' : 'processing item delete...',
                'question' : 'delete this item'
              };
    window.request.create (Connector);   
}

 
function ReloadLastListRequest()  
{   
    var Connector = { 
                'params' : Toolbar.read(), 
                'message' : 'Reloading most recent request...',
                'aftersend' : OnEventListLoaded, 
                'onreceive' : function () { HomePageEvent.invoke(); }
              };
    window.request.create (Connector); 
}

// User.Create.Load() 
function CreateUser(first, last)  
{   
    var nu = new MVCUser( MVCUser.empty (first, last) ); 
    nu.save();
} 

// Calendar.Create.Load() 
function CreateCalendar(name)  
{   
    var nu = new EventCalendar( EventCalendar.empty (name) ); 
    nu.save();
} 

if (document.all)  
{  
    document.onmousedown = function ()  
    {  
        if (window.event.srcElement)  
        {  
            var o=window.event.srcElement;  
            MouseRespond (o)  
        }  
    }  
}  
else  
{  
    document.onmousedown = function (e)  
    {  
        MouseRespond (e.target)  
    }  
}  
window.resizer = new DHTMLEvent();  
window.disabler = new DHTMLEvent();   
window.progress = new DHTMLEvent();   
window.onresize = function ()  
{  
    window.resizer.invoke ();  
    HideTimeSelector();  
}

function DisplayRoomSelector(element, selected, callback)
{
	HideTimeSelector();
	var ds=getElement ('droomselect'); 
	var dc=getElement (element); 
	if (dc)
	{
	    ds.style.display ='inline';
	    ds.style.width 	 = 200;
	    ds.style.left 	 = docx (dc) + dc.offsetWidth - ds.offsetWidth;
	    ds.style.top 	 = docy(dc) + dc.offsetHeight;
	}
}

//DisplayDateSelector DisplayTimeSelector CLLoadEventConflictRoomList ('12688')

function CLDisplayDateSelector(element, value, callback, offsets)
{
	 DisplayDateSelector(element, value, ResetEventCloneDate, offsets)
}

function ResetEventCloneDate ()
{    
	HideTimeSelector();
	Controller.domClone['EventDate'] = dateSQL (this.getvalue()); 
	Controller.Reload();
} 

		//var found = false;
//		for (var x in this.Rooms)
//		{
//			if (this.Rooms[x].value==value) found=true;
//		}
//		if (found) alert ('This room is already booked for this event');
//		else this.Rooms.push (new RoomObject (name, value));
function UploadCloneDateList (id, rooms)
{ 
	var i, n, em=[],ex = rooms.split (',');
	Controller.domClone.Rooms=[];
	for (var x in ex)
	{ 
		i = ex[x]; n=GetRoomName (i);
	    Controller.domClone.Rooms.push ( new RoomObject (n, i) ); 
		em.push (n);
	} 
	Controller.domClone.RoomName = em.join (', ');
	Controller.Reload();
}

//DisplayDateSelector DisplayTimeSelector

function DisplayDateSelector(element, value, callback, offsets)
{
	HideTimeSelector();
	var offsetY = 0;
	if (offsets)
	{
		for (var x in offsets)
		{
			var dx = document.getElementById (offsets[x]);
			if (dx) offsetY += dx.scrollTop;
		}
	}
	var oDate=value ? new Date (dateUS(value)) : new Date();
	if (isNaN(oDate)) oDate=new Date();
	
	var INPUT=element;
	window.eventdatepicker.onupdate=function () {}
	window.eventdatepicker.oDate=new Date (oDate.getFullYear(), oDate.getMonth(), 1);
	window.eventdatepicker.update ();
	window.eventdatepicker.setdate (oDate.getDate());
	window.eventdatepicker.onupdate=callback
	
	var de=getElement ('dcevent'); 
	var dc=getElement (element); 
	if (dc)
	{
	    var offy = de ? de.scrollTop : 0;
		if (offsetY > 0) offy = offsetY;
		  
	    var ds=getElement ('ddateselect'); 
	    ds.style.display ='inline'; 
	    ds.style.left 	 = docx (dc);
	    ds.style.top 	 = docy (dc) + dc.offsetHeight - offy;
	}
}


function CLDisplayTimeSelector(element, value, id, marker, command)
{
	DisplayTimeSelector(element, value, id, marker, 'ResetEventCloneTime');
}


function ResetEventCloneTime (id, value, marker)
{   
	HideTimeSelector();
	Controller.domClone['Event' + marker + 'Time'] = value;
	Controller.domClone['Setup' + marker + 'Time'] = value;
	Controller.Reload();
} 

function DisplayTimeSelector(element, value, id, marker, command)
{
	HideTimeSelector();
	var ch=command||'ResetEventConflictTime';
	var htm='<select multiple size=5 ';
	htm += ' onchange="' + ch + '('+id+', this.value, \'' + marker + '\')" ';
	htm += '>';
	var am,h,m,tm,H=0;
	for (var ap=0;ap<2;ap++)
	{
		am=ap==0?'am':'pm';
		for (var hh=0;hh<12;hh++)
		{
			h=hh==0?12:hh;
			for (var mm=0;mm<60;mm+=15)
			{
				m=mm==0?'00':mm;
				tm = h + ':' + m + '' + am;
				htm += '<option value="'+H+':'+m+'" '+(tm==value?' selected ':'')+'>' + tm;
			}
			H ++;
		}
	}
	htm += '</select>';
	var dc=getElement (element); 
	if (dc)
	{
	    var ds=getElement ('dtimeselect');
	    ds.innerHTML=htm;
	    ds.style.display='inline';
	    ds.style.left = docx (dc);
	    ds.style.top = docy(dc) + dc.offsetHeight;
	}
}






function dateCorrect(value)
{
	var x = new Date (value);
	if (isNaN(x)) return x;
	return dateSQL (x);
}


// -----------------------------------------------------------------------'
// EventList 
// -----------------------------------------------------------------------'
// EventList.SearchByName.Load() 
function SearchEvents ()  
{  
    var map = [
            {'element' : 'spn', 'value' : 'nm' },
            { 'element' : 'esd', 'value' : 's1', 'type' : 'date' },
            { 'element' : 'eed', 'value' : 's2', 'type' : 'date' },
            { 'element' : 'spr', 'value' : 'rm' },
            { 'element' : 'usr', 'value' : 'us' },
            { 'element' : 'sprnm', 'value' : 'pn', 'serializer' : function (x) { var e=GetCustomPropertyById(x); if (e) return e.property_name; } },
            { 'element' : 'sprvl', 'value' : 'pv' }, 
            { 'element' : 'adf', 'value' : 'af' }  
             ];
	
	var stamp = new Date();
    var value, object = { 'action' : 'event', 'op' : 'xms', 'stamp' : stamp.getTime() }, output=[];   
    for (var x in map)
    {
        if (getElement (map[x].element))
        {
            value = getElement (map[x].element).value;
            if (value!=''&&value!='0'&&value!='End Date'&&value!='Start Date')
                object [map[x].value] = map[x].serializer ? map[x].serializer (value) : ( map[x].type=='date' ? dateCorrect(value) : value );
        }
    } 
     
    for (var x in object)
    {
        output.push (x + '/' + object[x]);
    }  
    
    location.href = './#report/search/' + output.join ('/');
}   
 
function SearchEventsEx()  
{   
    var mt = getElement ('mto');
    if (mt) Controller.MailTo = mt.value;
    
    Controller.eventlist=[];
    var Connector = { 
        'params' : Controller.QueryString ,
        'aftersend' : OnEventListLoaded ,
        'message' : 'processing search results...',
        'rowname' : 'r',
        'columnname' : 'n',
        'target' : Controller.eventlist,
        'onreceive' : function () { Controller.LastListURL=window.request.createURL (); HomePageEvent.invoke(); }
              };
    window.request.create (Connector);      
}   

// Next5Events.Load() 
function LoadNext5Events(batch)  
{  
    Controller.eventlist=[];
    var Connector = { 
        'params' : { 'action' : 'next5', 'op' : 'xms', 'cr' : 'true' } ,
        'message' : 'processing search results...',
        'aftersend' : OnEventListLoaded ,
        'rowname' : 'r',
        'columnname' : 'n',
        'target' : Controller.eventlist,
        'onreceive' : function () { HomePageEvent.invoke(); }
              };
    if (batch) return Connector;
    else window.request.create (Connector);   
} 

// EventList.SearchByDate.Load() 
function SearchEventsByDate (date)  
{   
    Controller.eventlist=[];
    var Connector = { 
        'params' : { 'action' : 'event', 'op' : 'xms', 's1' : date } ,
        'message' : 'processing search results...',
        'aftersend' : OnEventListLoaded ,
        'rowname' : 'r',
        'columnname' : 'n',
        'target' : Controller.eventlist,
        'onreceive' : function () { HomePageEvent.invoke(); }
              };
    window.request.create (Connector);    
}  

// EventList.SearchByRoom.Load() 
function SearchEventsByRoom (room)  
{   
    Controller.eventlist=[];
    var Connector = { 
        'params' : { 'action' : 'event', 'op' : 'xms', 'rm' : room } ,
        'message' : 'processing search results...',
        'aftersend' : OnEventListLoaded ,
        'rowname' : 'r',
        'columnname' : 'n',
        'target' : Controller.eventlist,
        'onreceive' : function () { HomePageEvent.invoke(); }
              };
    window.request.create (Connector);   
}  
   
// EventList.SearchByUser.Load() 
function SearchEventsByUser (user)  
{   
    Controller.eventlist=[];
    var Connector = { 
        'params' : { 'action' : 'event', 'op' : 'xms', 'us' : user } ,
        'message' : 'processing search results...',
        'aftersend' : OnEventListLoaded ,
        'rowname' : 'r',
        'columnname' : 'n',
        'target' : Controller.eventlist,
        'onreceive' : function () { HomePageEvent.invoke(); }
              }; 
    window.request.create (Connector); 
}
   
// EventList.Featured.Load() 
function LoadFeaturedEvents ()  
{   
    Controller.eventlist=[];
    var Connector = { 
        'params' : { 'action' : 'sql_featured' } ,
        'aftersend' : OnEventListLoaded ,
        'message' : 'processing search results...',
        'rowname' : 'r',
        'columnname' : 'n',
        'target' : Controller.eventlist,
        'onreceive' : function () { HomePageEvent.invoke(); }
              }; 
    window.request.create (Connector);  
} 

function LoadEventDetailCustomProperties (callback, batch)  
{    
	window.currentevent.CustomProperties = [];
    var Connector = { 
        'params' : { 'action' : 'prop', 'id' : window.currentevent.ID },
        'target' : window.currentevent.CustomProperties, 
        'message' : 'loading event custom properties...',
        'aftersend' : callback || LoadEventDetailDateRange,
        'serializer' : function (target, data) { target.push ( new CustomProperty (data['propname'], data['propvalue'])) ;  },
        'onreceive' : function () { EventDetailEvent.invoke(); }
              };
    if (batch) return Connector;
    else window.request.create (Connector); 
}   

function LoadCurrentEvent ()
{
    var Connectors=[];

    Connectors.push (LoadEventDetailCustomProperties (null, true)); 
    Connectors.push (LoadEventDetailDateRange (null, true)); 
    Connectors.push (LoadEventDetailRoomList (null, true));
    Connectors.push (LoadEventDetailCommentList (null, true));
    Connectors.push (LoadEventDetailAttachments (null, true));
    Connectors.push (LoadEventDetailCalendarList (true));
    Connectors.push (LoadEventDetailCategoryList (null, true)); 
    
    window.isbusy = true;
    window.disabler.invoke (window.isbusy); 
    window.connector.oncomplete = function () { Controller.Clear(); EventDetailEvent.invoke(); };
    window.connector.send (Connectors);
}

// EventDetailCustomProperties.Build() 
function ProcessEventDetailCustomProperties () // 1st  
{               
    alert ('legacy method ProcessEventDetailCustomProperties called!'); 
} 

function OnEventListLoaded ()
{
	window.datagrids = null;
	Controller.Clear();    
	Controller.LastListURL=Controller.LastRequestURL;
	window.eventlistxml = window.http.responseText;   
	
}

// EventList.Build() 
function ProcessEventListResultEx ()  
{     
    alert ('legacy method ProcessEventListResultEx called!');      
}  

function CheckForMailRequest ()
{
    var dg = window.datagrids[0];
    var sa = dg.showall;
    dg.showall=true;
    var bd = dg.draw ();
    dg.showall = sa;
    if (Controller.MailTo && Controller.MailTo.length > 0)
    {
        var xml = '';
        xml += '<email>';
        xml += '<header to="' + Controller.MailTo + '" from="" subject="' + APPLICATION_NAME + ' support"/>';
        xml += '<body><![CDATA[';
        xml += bd;
        xml += ']]></body>';
        xml += '</email>';
        
        var Connector = {  
            'aftersend' : function () { alert (window.http.responseText); } ,
            'message' : 'Processing email...',
            'method' : 'POST',
            'postdata' : xml
                  }; 
        window.request.create (Connector);   
    }
    Controller.MailTo = null;
}

// EventList.SearchByIndex.Load() 
function LoadEventByIndex (gridid, row)  
{   
    var dg=window.datagrids[gridid];  
    if (dg.rows[row])  
    {  
        window.currentevent = new EventObject(dg.rows[row],row,dg.rows.length,gridid);  
        LoadCurrentEvent ();
    }  
}   

// EventList.SearchById.Load() 
function EventDataGridEdit (gridid, eventid)  
{   
    if (window.loggedinuser.PERM_MODIFY)
    {
        if (! Controller.eventlist )
        {
            return confirm ('No eventlist to parse!');
        }
        var that;//, dg=window.datagrids[gridid];  
//        for (var row=0;row<dg.rows.length;row++)
        for (var row=0;row<Controller.eventlist.length;row++)  
        {    
            that = Controller.eventlist[row];
//            if (dg.rows[row]['ID']==eventid) 
            if (that['ID']==eventid)  
            {  
                window.currentevent = new EventObject(Controller.eventlist[row], row, Controller.eventlist.length, gridid);  
//                window.currentevent = new EventObject(dg.rows[row], row, dg.rows.length, gridid);   
                LoadCurrentEvent ();
                break;  
            }  
        } 
        return true;  
    }  
    alert ('Sorry, ' + window.loggedinuser.name + ', you do not have permission to edit events.');
}  
// -----------------------------------------------------------------------'


function ToggleSearch()  
{  
    window.searchmode=window.searchmode>0?0:1;  
    Controller.Reload(); 
    setCookie('searchmode', window.searchmode); 
    window.resizer.invoke(); 
}  

function ToggleSidebarState()
{
    Controller.SidebarState=-(Controller.SidebarState-1);
    Controller.Reload ();
}

function Reload ()
{
    alert ('legacy function Reload was called!!');
}
 
 
function refreshCalendars ()  
{   
    var seed = new Date ();  
    var id = new Calendar(seed.getFullYear(), seed.getMonth() + 1, seed.getDate(), "dcal", 'CalendarStyle0', null, true );  
    id.onupdate = function ()  
    {  
        var d=new Date(this.Year, this.Month, this.Day);  
        SearchEventsByDate (d.getFullYear()+'-'+(d.getMonth() + 1)+'-'+d.getDate());  
    }  
    id.linktype=true;
    id.draw ('dcal');   
      
    window.eventdatepicker = new Calendar(2002, 6, 22, "ddateselect", 'CalendarStyle0' ); 
    window.eventdatepicker.draw ('ddateselect');    
}
 
 
function LoadPublicCalendar ()  
{   
   //  confirm ( Controller.SelectedCalendar )
	if (Controller.SelectedCalendar>0)
	{
	    var array = GetCalendarById(Controller.SelectedCalendar);
	    var map = new EventCalendar (array, 'dworkspace'); 
		var re = /calendar\/(\d+)\/date\/(.*)/ ;
		var mm = re.exec (location.href); 
		if (mm)
		{
			map.date = new Date (dateUS (mm[2]));
		}
		map.debug = false;
	    map.invoke ();
	}     
}
 
 
function ProcessPublicCalendarList ()  
{    
    if (window.http.readyState==ReadyState.DONE)   
    {    
    	ProcessGlobalCalendarListEx (LoadPublicCalendar);  
	}
}
 
 
function attachWaitInvoke ()  
{ 
	var ds=getElement ('dwaitinvoke');
	if (ds)
	{
		ds.invoke = function (x)
		{ 
			this.style.display = window.isbusy ? 'inline' : 'none';
			this.style.left = '0px';
			this.style.top = '0px';
			this.style.width = window_w();
			this.style.height = window_h();
			var wait = '<table width="100%" height="100%"><tr><td align=center style="color:#999;font-size:8pt">';
			wait += '<!--<img src="/webservices/images/filecopy.gif">-->'; 
			wait += '<br>';
			wait += '' + (window.processmessage || 'Loading...') + '';
			wait += '';
			wait += '</td></tr><tr><td height="20" align="right">';
			wait += '<input type="button" onclick="Controller.Clear()" value="Cancel"/>'; 
			wait += '</td></tr></table>';
			this.innerHTML = wait;
		}
		window.resizer.subscribe (ds);
		window.disabler.subscribe (ds);
	}
}
 
 
function de ()  
{ 
	var debug = '';
	
	for (var x in window) 
	{
		if (typeof (window[x])=='function') { /* do nothing */ }
		else 
		{
			try
			{
				if (!isNaN(window[x].length)) debug += x+' (' + typeof (window[x]) + '): '+/*window[x] + */ + window[x].length + '<br>'
			} catch (ex) { }
		}
	}
	if (window.request.sql) 
	{
	    for (var x in window.request.sql) 
	    {
		     debug += x+'. <xmp>' + window.request.sql[x] + '</xmp><br>' 
	    }
	} 
	var k=window.open ();
	k.document.write (debug);
}

function messagebox (url)
{ 
	var re = Toolbar.read (url);
	var Connector = { 
				'params' : Toolbar.read (url),   
				'aftersend' : function () { dialog (window.http.responseText) }
			  };
        window.request.create (Connector); 
}

function dialog (text,message)
{ 
	Controller.moreinfo=text;
	Controller.message=message||'The information contained in these dialogs is meant <b>for the programmer</b>. This information is used to ' + 
		' continue the maintainance of the system. If you are seeing this information in error, please close this ' + 
		' window and continue your work.';
	window.lastevent = window.mvcevent; 
	WindowAlert.invoke (); 
}
 



function start ()  
{   
    document.title = APPLICATION_NAME;
     
    window.invoice = new Invoice ();
    refreshCalendars ();    
	Controller.Clear();
	if (getCookie('panels')) Controller.EventOptionPanelState = parseInt ( getCookie('panels') );
	if (getCookie('searchmode')) window.searchmode = parseInt ( getCookie('searchmode') );
	 
    downloadTemplates ();
}  

function BulkExecute (batch)
{  
    var Connector = {  
        'aftersend' : ReloadLastListRequest ,
        'message' : 'Receiving save response...',
        'method' : 'POST',
        'postdata' : batch
              }; 
    window.request.create (Connector); 
}   

function BulkFeature (array)
{
	var xml = '';
	xml += '<bulk.execute>';
	xml += '<sql><![CDATA[update events set Featured = (value) where id = (id)]]></sql>';
	for (var x in array) xml += '<command id="' + array[x][0] + '" value="' + array[x][1] + '"/>'; 
	xml += '</bulk.execute>';
    BulkExecute(xml);
} 

function BulkDelete (array)
{
	var xml = '';
	xml += '<bulk.execute>';
	xml += '<sql><![CDATA[ DELETE FROM jct_event_folders where eventfk=(id) ]]></sql>';
	xml += '<sql><![CDATA[ DELETE FROM jct_event_users where eventfk=(id) ]]></sql>';
	xml += '<sql><![CDATA[ DELETE FROM event_rooms where eventfk=(id) ]]></sql>';
	xml += '<sql><![CDATA[ DELETE FROM recursors where eventFk=(id) ]]></sql>';
	xml += '<sql><![CDATA[ DELETE FROM recursecustom where eventFk=(id) ]]></sql>';
	xml += '<sql><![CDATA[ DELETE FROM customproperties where eventFk=(id) ]]></sql>';
	xml += '<sql><![CDATA[ DELETE FROM jct_event_calendar where eventFk=(id) ]]></sql>';
	xml += '<sql><![CDATA[ DELETE FROM events where ID=(id) ]]></sql>';
	for (var x in array) xml += '<command id="' + array[x] + '"/>'; 
	xml += '</bulk.execute>';
    BulkExecute(xml);
} 

function BulkApprove (array)
{
	var xml = '';
	xml += '<bulk.execute>';
	xml += '<sql><![CDATA[update events set ApproveDate=(date), ApproveLogin = (value) where id = (id)]]></sql>';
	for (var x in array) xml += '<command id="' + array[x][0] + '" date="' + array[x][1] + '" value="' + array[x][2] + '"/>'; 
	xml += '</bulk.execute>';
    BulkExecute(xml);
}                         
                                    
function BeginBulkExecute(index, gridid)
{
	if (isNaN(index) && index.indexOf('r')==0)
	{
		var id=index.substr(2);
		EventDataGridChangeReport (id);
		return true;
	}
    var command	= [];
	var array	= [];
	var boxes 	= document.getElementsByTagName ('INPUT');
	for (var x=0;x<boxes.length;x++)
	{
		if (boxes[x].type=='checkbox' && 
			boxes[x].checked && 
			boxes[x].className=='bulk'
			) array.push (boxes[x].value);
	}
	if (array.length > 0)
	{
		switch (parseInt(index))
		{
			case 0:
				for (var x=0;x<array.length;x++) command.push(new Array (array[x], 1));  
				BulkFeature (command);
				break;
			case 1:
				for (var x=0;x<array.length;x++) command.push(new Array (array[x], 0));  
				BulkFeature (command);
				break;
			case 2:
				for (var x=0;x<array.length;x++) command.push(new Array (array[x], dateSQL(new Date()), window.loggedinuser.id));  
				BulkApprove (command);
				break;
			case 3:
				for (var x=0;x<array.length;x++) command.push(new Array (array[x], dateSQL(new Date()), 0));  
				BulkApprove (command);
				break;
			case 4: 
				if (doconfirm ('delete these ' + array.length + ' items?')) BulkDelete (array);
				break;
			case 5: 
			    var ar=[];
                var dg=window.datagrids[gridid];  
                var hs=','+array.join (',')+',';
                for (var row in dg.rows)  
                {  
                    if (hs.indexOf (','+dg.rows[row]['ID']+',')>=0)  ar.push (dg.rows[row]);
                }  
                window.invoice.gridid = gridid;
                window.invoice.add (ar);
		}
	}
	else alert ('No items selected');
}


function doconfirm (message)
{
	if (confirm ("Are you sure you want to " + message + "?"))
	{
		if (confirm ("THIS ACTION CANNOT BE UNDONE! Are you really REAALLY sure you want to PERMANENTLY delete?"))
		{
			return confirm ("Last chance!! You need to be ABSOLUTELY SURE. Shall I delete?");
		}
	}
	return false;
}